package com.example.shopspring.service.impl;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.shopspring.common.ResultData;
import com.example.shopspring.dto.AdminInDto;
import com.example.shopspring.dto.UpdatePasswordInDto;
import com.example.shopspring.entity.Admin;
import com.example.shopspring.mapper.AdminMapper;
import com.example.shopspring.service.AdminService;
import com.example.shopspring.utils.JWTUtil;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    //登录接口
    @Override
    public ResultData login(AdminInDto adminInDto) {
        //1,校验数据库（username,password）
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getUsername, adminInDto.getUsername())
                .eq(Admin::getPassword, adminInDto.getPassword());
        Admin admin = getOne(queryWrapper);
        if (admin == null) {
            return ResultData.error(401, "用户名，密码错误！");
        } else {
            //2,如果检验通过，用JWT工具生成Token
            HashMap<String, String> payload = new HashMap<>();
            payload.put("id",String.valueOf(admin.getId()));
            payload.put("username",admin.getUsername());
            payload.put("password",admin.getPassword());
            String token = JWTUtil.getToken(payload);
            Map<String, String> tokenMap = new HashMap<>();
            tokenMap.put("token", token);
            //3,返回token
            return ResultData.success(tokenMap);
        }
    }

    @Override
    public Admin getAdminInfo(String token) {
        Admin admin = getById(JWTUtil.getId(token));
        return admin;
    }

    @Override
    public ResultData updatePassword(String token, UpdatePasswordInDto passwordInDto) {
        //验证新密码和确认密码是否一致，不一致，告知两次密码不一致
        if (!passwordInDto.getNewPassword().equals(passwordInDto.getRePassword()))
            return ResultData.error(405,"两次密码不一致！");
        //1根据token，获取用户的id
        Integer id = JWTUtil.getId(token);
        //2根据id，查数据，获取用户对象admin
        Admin admin = getById(id);
        //3旧密码和admin里面的密度对比，如果不通过，返回原密码不正确
        if(!admin.getPassword().equals(passwordInDto.getOldPassword()))
            return ResultData.error(406,"原密码错误！");
        //验证通过，修改密码
        admin.setPassword(passwordInDto.getNewPassword());
        boolean b = updateById(admin);
        //让原来的token失效
        JWTUtil.invalidateToken(token);
        if (b)
            return ResultData.success(true);
        else
            return ResultData.error(407,"密码修改失败");
    }
}
